package com.foin.city;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.foin.city.adapter.CityAdapter;
import com.foin.city.bean.City;
import com.foin.city.itemclick.OnItemClickListener;
import com.foin.city.iview.ICityView;
import com.foin.city.presenter.ICityPresenter;
import com.foin.city.presenter.impl.CityPresenterImpl;
import com.foin.city.utils.StatusbarColorUtils;
import com.foin.city.widget.LetterIndexView;
import com.foin.city.widget.navigation.NavigationBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CityActivity extends AppCompatActivity implements ICityView {
    @BindView(R.id.sticky_header)
    TextView mStickyHeaderTv;
    @BindView(R.id.city_recycler_view)
    RecyclerView mCityRv;
    @BindView(R.id.letter_navi)
    LetterIndexView mLetterNavi;
    @BindView(R.id.letter_navi_tip)
    TextView mLetterNaviTipTv;

    private ICityPresenter mPresenter;
    private CityAdapter mCityAdapter;
    private List<City> mCityList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置为竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_city);
        StatusbarColorUtils.setStatusBarDarkIcon(this, true);
        ButterKnife.bind(this);
        initView();
        initData();
        initTitle();
    }

    protected void initView() {
        mCityRv.setLayoutManager(new LinearLayoutManager(this));
        mCityList = new ArrayList<>();
        mCityAdapter = new CityAdapter(this, mCityList);
        mCityAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position, View view) {
                Toast.makeText(CityActivity.this, "点击了：" + mCityList.get(position).getName(), Toast.LENGTH_SHORT).show();
            }
        });
        mCityRv.setAdapter(mCityAdapter);
        mCityRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 找到RecyclerView的item中，和RecyclerView的getTop 向下相距5个像素的那个item
                // (尝试2、3个像素位置都找不到，所以干脆用了5个像素)，
                // 我们根据这个item，来更新吸顶布局的内容，
                // 因为我们的StickyLayout展示的信息肯定是最上面的那个item的信息.
                View stickyInfoView = recyclerView.findChildViewUnder(mStickyHeaderTv.getMeasuredWidth() / 2, 5);
                if (stickyInfoView != null && stickyInfoView.getContentDescription() != null) {
                    mStickyHeaderTv.setText(String.valueOf(stickyInfoView.getContentDescription()));
                }
                // 找到固定在屏幕上方那个FakeStickyLayout下面一个像素位置的RecyclerView的item，
                // 我们根据这个item来更新假的StickyLayout要translate多少距离.
                // 并且只处理HAS_STICKY_VIEW和NONE_STICKY_VIEW这两种tag，
                // 因为第一个item的StickyLayout虽然展示，但是一定不会引起FakeStickyLayout的滚动.
                View transInfoView = recyclerView.findChildViewUnder(mStickyHeaderTv.getMeasuredWidth() / 2, mStickyHeaderTv.getMeasuredHeight() + 1);
                if (transInfoView != null && transInfoView.getTag() != null) {
                    int transViewStatus = (int) transInfoView.getTag();
                    int dealtY = transInfoView.getTop() - mStickyHeaderTv.getMeasuredHeight();
                    // 如果当前item需要展示StickyLayout，
                    // 那么根据这个item的getTop和FakeStickyLayout的高度相差的距离来滚动FakeStickyLayout.
                    // 这里有一处需要注意，如果这个item的getTop已经小于0，也就是滚动出了屏幕，
                    // 那么我们就要把假的StickyLayout恢复原位，来覆盖住这个item对应的吸顶信息.
                    if (transViewStatus == mCityAdapter.HAS_STICKY_VIEW) {
                        if (transInfoView.getTop() > 0) {
                            mStickyHeaderTv.setTranslationY(dealtY);
                        } else {
                            mStickyHeaderTv.setTranslationY(0);
                        }
                    } else if (transViewStatus == mCityAdapter.NONE_STICKY_VIEW) {
                        // 如果当前item不需要展示StickyLayout，那么就不会引起FakeStickyLayout的滚动.
                        mStickyHeaderTv.setTranslationY(0);
                    }
                }
            }
        });
        mLetterNavi.setOnTouchingLetterChangedListener(new LetterIndexView.OnTouchingLetterChangedListener() {
            @Override
            public void onHit(String letter) {
                mLetterNaviTipTv.setVisibility(View.VISIBLE);
                mLetterNaviTipTv.setText(letter);
                scrollToPosition(letter);
            }

            @Override
            public void onCancel() {
                if (mLetterNaviTipTv != null) {
                    mLetterNaviTipTv.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    protected void initData() {
        mPresenter = new CityPresenterImpl(this);
        selectCity();
    }

    protected void initTitle() {
        new NavigationBar.Builder(this)
                .setTitle(R.string.choose_city)
                .builder();
    }

    @Override
    public void onGetCitySuccess(List<City> list) {
        if (list != null) {
            mCityList.addAll(list);
        }
        mCityAdapter.notifyDataSetChanged();
    }

    /**
     * 滚动列表到指定位置
     */
    private void scrollToPosition(String letter) {
        int position = 0;
        for (int i = 0; i < mCityList.size(); i++) {
            if (TextUtils.equals(letter, mCityList.get(i).getLetter())) {
                position = i;
                break;
            }
        }
        ((LinearLayoutManager) mCityRv.getLayoutManager()).scrollToPositionWithOffset(position, 0);
    }

    /**
     * 查询全国城市列表
     */
    private void selectCity() {
        mPresenter.selectCity();
    }
}
